package tcp;

import java.util.Arrays;

import com.serotonin.io.serial.SerialParameters;
import com.serotonin.modbus4j.ModbusFactory;
import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.exception.ModbusInitException;
import com.serotonin.modbus4j.exception.ModbusTransportException;
import com.serotonin.modbus4j.ip.IpParameters;
import com.serotonin.modbus4j.msg.ReadHoldingRegistersRequest;
import com.serotonin.modbus4j.msg.ReadHoldingRegistersResponse;

public class tre_3 {
	public static String ipAdress;
	public static int ipPort;
	public static int slaveId;
	public static int start;
	public static int len;
	public tre_3(String ipAdress1, int ipPort1, int slaveId1, int start1, int len1)
	{
		ipAdress = ipAdress1; 
		ipPort = ipPort1;
		 slaveId = slaveId1;
		 start = start1;
		 len  = len1;
	};
	public static int[] remain1(){
		short result[] = null;
		IpParameters ipParameters = new IpParameters();
        ipParameters.setHost(ipAdress);
        ipParameters.setPort(ipPort);
		ModbusFactory modbusFactory = new ModbusFactory();

		ModbusMaster master = modbusFactory.createTcpMaster(ipParameters, false);
        try {
			master.init();
		} catch (ModbusInitException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        result = readHoldingRegistersTest(master, slaveId, start, len);
        //   System.out.println(result[0]);
          
          // String[] strarr = result.split(",");
          int resultint[] = new int[result.length];
           for(int i=0; i<result.length; i++)
              {//System.out.println(result[i]);
        	  
        	   resultint[i] =(int)result[i]; 
        	  // System.out.println("1111");
        	   
        	   System.out.println(resultint[i]);
        	   }

                master.destroy();
                
                return resultint;
            
    	};
	
	public static short[] readHoldingRegistersTest(ModbusMaster master, int slaveId3, int start3, int len3) {
        short[] result1 = null; 
	  
		try {
            ReadHoldingRegistersRequest request = new ReadHoldingRegistersRequest(slaveId3, start3, len3);
            ReadHoldingRegistersResponse response = (ReadHoldingRegistersResponse) master.send(request);

            if (response.isException())
                System.out.println("Exception response: message=" + response.getExceptionMessage());
            else
                System.out.println(Arrays.toString(response.getShortData()));
            //System.out.println(response.getShortData());
            result1 = response.getShortData();
            //System.out.println("result1[0]+"+result1[0] );
        }
        catch (ModbusTransportException e) {
            e.printStackTrace();
        }
        return result1;
    }
}
